package com.shu.logsearch.common.base;

import com.shu.logsearch.common.annotation.BaseViewDirectory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import java.lang.annotation.Annotation;

/**
 * 继承该类，即可拥有各种通用controller方法，但子类必须遵循“*ViewController"
 *
 * @author Tree Cai
 * @date 2019/7/10
 * @see BaseViewDirectory
 * 子类使用注解ViewDirectory指定视图路径
 */

public class BaseController<M extends BaseModel, S extends BaseService> {

    @Autowired
    public S service;

    private String viewDirectory;

    public String setViewDirectory(String viewDirectory) {
        if (StringUtils.isEmpty(viewDirectory))
            return "";
        if (!viewDirectory.startsWith("/"))
            viewDirectory = "/" + viewDirectory;
        if (!viewDirectory.endsWith("/"))
            viewDirectory += "/";
        this.viewDirectory = viewDirectory;
        return viewDirectory;
    }

    /**
     * 初始化子类时，获取子类controller的@ViewDirectory注解指定的视图路径
     */
    @PostConstruct
    private void init() {
        Annotation annotation = this.getClass().getAnnotation(BaseViewDirectory.class);
        if (annotation != null && StringUtils.isNotEmpty(setViewDirectory(((BaseViewDirectory) annotation).value())))
            return;
        String className = this.getClass().getSimpleName().replace("ViewController", "");
        if (className.length() < 2 && StringUtils.isNotEmpty(setViewDirectory("/default")))
            return;
        setViewDirectory(className.substring(0, 1).toLowerCase() + className.substring(1));
    }

    @RequestMapping("/view/list")
    public String viewList() {
        return viewDirectory + "list";
    }

    @RequestMapping("/view/edit/{id}")
    public String viewEdit(@PathVariable Integer id, Model model) {
        model.addAttribute("id", id);
        model.addAttribute("model", service.getById(id));
        return viewDirectory + "edit";
    }

    @RequestMapping("/view/add")
    public String viewAdd() {
        return viewDirectory + "edit";
    }

}
